package com.onlineauction.entities;

import java.util.logging.Logger;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.onlineauction.helpers.CacheHandler;
import com.onlineauction.helpers.Constants;

public class GenericEntity {

	protected static Logger LOGGER = Logger.getLogger(GenericEntity.class
			.getName());

	@Deprecated
	protected static Key storeEntity(Entity entity) {
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		return ds.put(entity);
	}

	/**
	 * Guarrantee entity can been seen by others if true is returned.
	 * Meant to replace storeEntity
	 * 
	 * @return true if the the entity is stored and can be seen by calling
	 *         DataStoreService.get false if not
	 */
	protected static boolean saveEntity(Entity entity) {
		boolean isSaved = false;

		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		Key key = ds.put(entity);
		int retries = Constants.MAX_RETRIES;
		while (retries > 0) {
			try {
				if (ds.get(key) != null) {
					// the entity has been saved successfully
					isSaved = true;
					break;
				}
			} catch (EntityNotFoundException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			retries--;
		}
		return isSaved;
	}

	protected static Entity getEntity(String kind, String keyName) {
		if (keyName == null || keyName.length() == 0) {
			return null;
		}

		Key key = KeyFactory.createKey(kind, keyName);
		try {
			Entity entity = DatastoreServiceFactory.getDatastoreService().get(
					key);
			return entity;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}

	protected static Entity getEntity(String kind, long id) {
		Key key = KeyFactory.createKey(kind, id);
		try {
			Entity entity = DatastoreServiceFactory.getDatastoreService().get(
					key);
			return entity;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}

}
